package service

import (
    "authserver/constants"
    "authserver/global"
    "authserver/model"
    "authserver/utils"
    "encoding/json"
    "errors"
    "fmt"
    "github.com/tidwall/gjson"
    "net/url"
    "regexp"
    "strings"
    "time"
)

//
// DyUrlParse
//  @Description:
//  @param shortUrl
//  @param username
//  @return err
//  @return respVideo
//
func DyUrlParse(shortUrl string,username string) (err error,respVideo model.VideoResp) {

	//if isDouyinURL(shortUrl) {
	//	return errors.New("不是抖音链接:" + shortUrl),respVideo
	//}

    var logInfo model.ParseLog

    global.GVA_DB.Table(logInfo.TableName()).Where("short_url=?",shortUrl).Find(&logInfo)
    if logInfo.Id!=0{

        // 超时时间
        logTime,_:=time.ParseInLocation(constants.DayTime,logInfo.ParseTime,time.Local)

        if time.Now().Sub(logTime).Minutes()<30{
            respVideo=model.VideoResp{
                Id:logInfo.Id,
                Title: logInfo.Title,
                Image: logInfo.ImageUrl,
                Video: logInfo.VideoUrl,
            }
            return
        }
    }

	header := map[string]string{

		"Host":                      "v.douyin.com",
		"Connection":                "Keep-Alive",
		"Sec-Ch-Ua":                 `"Google Chrome";v="117", "Not;A=Brand";v="8", "Chromium";v="117"`,
		"Sec-Ch-Ua-Mobile":          "?1",
		"Sec-Ch-Ua-Platform":        `"Android"`,
		"Upgrade-Insecure-Requests": "1",
		//"User-Agent":                "Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/117.0.0.0 Mobile Safari/537.36",
		"User-Agent":                "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/107.0.0.0 Safari/537.36",
		"Accept":                    "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7",
		"Sec-Fetch-Site":            "none",
		"Sec-Fetch-Mode":            "navigate",
		"Sec-Fetch-User":            "?1",
		"Sec-Fetch-Dest":            "document",
		//"Accept-Encoding": "gzip, deflate, br",
		"Accept-Language": "zh-CN,zh;q=0.9",

		//
		"Cookie":     "__ac_nonce=0654cfdb800d946bf165b; __ac_signature=_02B4Z6wo00f01HVQDlQAAIDA9VL0FzroMkh1cArAAHggU3G8yH3ai7dMZG.Wp9aeS0qA82QrcBs3cQ3bE7FjpkTaBIRlrP7Emw7Nz2.vzNNC.Y0CFw1GCOYJu88xqIj8FvnMmpgTis9LlUoa0e",
	}

	err, _, headerh := utils.Get(shortUrl, nil, nil,nil)
	if err != nil {
		fmt.Println(err.Error())
		return err, respVideo
	}

    nextUrl := headerh["Location"]
	nextUrl = strings.Replace(nextUrl, "&amp;", "&", -1)

	u, err := url.Parse(nextUrl)
	if err != nil {
		fmt.Println("222", err.Error())
	}
	ss := strings.Split(u.Path, "/")
	//fmt.Println(ss,u.Path)
    itemId := ""
    if len(ss)==5{
        itemId=ss[3]
    }else{
        fmt.Println(itemId, len(ss))
        err= errors.New("获取失败")
        return
    }

    // 获取播放地址
    nextUrl="https://www.douyin.com/aweme/v1/web/aweme/detail"

    step2Param:= map[string]string{
        "aweme_id":itemId,
        "screen_width":"1920",
        "screen_height":"1080",
        "device_platform":"webapp",
        "aid":"6383",
    }


    header["Host"] = "www.douyin.com"
    header["Referer"] = "https://www.douyin.com/video/"+itemId
    header["Cookie"] = "ttwid=1%7Cf7lzJZTufXWL1GyaM1pLh1DH2BzSdZh3-BldvbwC5yc%7C1709004040%7Cd6041aa3afc3b6e26e617182621a8219d71289c6ba49a755598911a830901e0d"


    err, resp2, _ := utils.Get(nextUrl, step2Param, header,nil)
    if err != nil {
        fmt.Println(err.Error())
        return err, respVideo
    }

    fmt.Println("222",resp2)
    var step2Resp model.Step2Resp

    err=json.Unmarshal([]byte(resp2),&step2Resp)
    if err!=nil{
        global.GVA_LOG.Error(err.Error())
        err = errors.New("解析失败")
        return
    }

    item:=step2Resp.AwemeDetail
    desc:=item.Desc

    if len(item.Video.Cover.UrlList)==0{
        err = errors.New("解析失败")
        return
    }

    image:=item.Video.Cover.UrlList[0]
    if len(item.Video.Cover.UrlList)==0{
        err = errors.New("解析失败")
        return
    }

    videoId:=item.Video.PlayAddr.UrlList[0]

    videoTagStr:=make([]string,0)
    for _,v:=range item.VideoTag{
        videoTagStr = append(videoTagStr, v.TagName)
    }

    respVideo=model.VideoResp{
        Title: desc,
        Image: image,
        Video: videoId,
        SeoInfo:item.SeoInfo.OcrContent,
        VideoTag: strings.Join(videoTagStr,","),
    }

    hostAddr:=""
    u,err=url.Parse(respVideo.Video)
    if err!=nil{
        global.GVA_LOG.Error(err.Error())
        return
    }
    hostAddr = u.Host

    parseLog:=model.ParseLog{
        ShortUrl:  shortUrl,
        VideoUrl:  respVideo.Video,
        ImageUrl:  respVideo.Image,
        Title:     respVideo.Title,
        Username:  username,
        HostAddr: hostAddr,
        VideoTag: strings.Join(videoTagStr,","),
        SeoInfo:item.SeoInfo.OcrContent,
        ParseTime: time.Now().Format(constants.DayTime),
    }

    global.GVA_DB.Create(&parseLog)
    respVideo.Id = parseLog.Id
    return nil, respVideo

}

// isDouyinURL 检查是否为抖音链接
func isDouyinURL(url string) bool {
	return regexp.MustCompile(`https?://.*\.douyin\.com/.*`).MatchString(url)
}

func DyUrlParse2(shortUrl string,username string) (err error,respVideo model.VideoResp) {

	//videoUrl:=GetVideoUrl(shortUrl)
    videoUrl:=""
    global.GVA_LOG.Debug("解析完成。。。。。")
	if videoUrl==""{
		err = errors.New("解析失败")
		return
	}

	//fmt.Println("222",videoUrl)
	var step2Resp model.Step2Resp

	err=json.Unmarshal([]byte(videoUrl),&step2Resp)
	if err!=nil{
		global.GVA_LOG.Error(err.Error())
		err = errors.New("解析失败")
		return
	}

	item:=step2Resp.AwemeDetail
	desc:=item.Desc

	if len(item.Video.Cover.UrlList)==0{
		err = errors.New("解析失败")
		return
	}

	image:=item.Video.Cover.UrlList[0]
	if len(item.Video.Cover.UrlList)==0{
		err = errors.New("解析失败")
		return
	}

	videoId:=item.Video.PlayAddr.UrlList[0]

	videoTagStr:=make([]string,0)
	for _,v:=range item.VideoTag{
		videoTagStr = append(videoTagStr, v.TagName)
	}

	respVideo=model.VideoResp{
		Title: desc,
		Image: image,
		Video: videoId,
		SeoInfo:item.SeoInfo.OcrContent,
		VideoTag: strings.Join(videoTagStr,","),
	}

	hostAddr:=""
	u,err:=url.Parse(respVideo.Video)
	if err!=nil{
		global.GVA_LOG.Error(err.Error())
		return
	}
	hostAddr = u.Host

	parseLog:=model.ParseLog{
		ShortUrl:  shortUrl,
		VideoUrl:  respVideo.Video,
		ImageUrl:  respVideo.Image,
		Title:     respVideo.Title,
		Username:  username,
		HostAddr: hostAddr,
		VideoTag: strings.Join(videoTagStr,","),
		SeoInfo:item.SeoInfo.OcrContent,
		ParseTime: time.Now().Format(constants.DayTime),
	}

	global.GVA_DB.Create(&parseLog)
	respVideo.Id = parseLog.Id
	return nil, respVideo

}


// 第三方API
func DyUrlParse3(shortUrl string,username string) (err error,respVideo model.VideoResp) {

    action:="https://dog886.com/tools/video"

    postForm:=make(map[string]string)
    postForm["url"] = shortUrl

    header:= map[string]string{
        "Content-Type":"application/x-www-form-urlencoded; charset=UTF-8",
    }
    err,resp:=utils.PostForm(action,nil,header,postForm)
    global.GVA_LOG.Debug(resp)
    if err!=nil{
        global.GVA_LOG.Error(err.Error())
        return
    }

    dataStr:=gjson.Get(resp,"data").String()

    var dogInfo model.DogApiResp

    err=json.Unmarshal([]byte(dataStr),&dogInfo)

    if err!=nil{
        global.GVA_LOG.Error(err.Error())
        return err,respVideo
    }

    respVideo.Video = dogInfo.Url
    respVideo.Image= dogInfo.Cover
    respVideo.Title = dogInfo.Title


    hostAddr:=""
    u,err:=url.Parse(respVideo.Video)
    if err!=nil{
        global.GVA_LOG.Error(err.Error())
        return
    }
    hostAddr = u.Host

    parseLog:=model.ParseLog{
        ShortUrl:  shortUrl,
        VideoUrl:  respVideo.Video,
        ImageUrl:  respVideo.Image,
        Title:     respVideo.Title,
        Username:  username,
        HostAddr: hostAddr,
        VideoTag: "",
        SeoInfo: "",
        ParseTime: time.Now().Format(constants.DayTime),
    }

    global.GVA_DB.Create(&parseLog)
    respVideo.Id = parseLog.Id

    return nil,respVideo
}
